package top.callname.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class BaseUtil {
	
	
	/**
	 * 分页参数容错
	 * @param pageNo
	 * @return int
	 */
	public final static int getPageNo(String pageNo){
		int page = 1;
		if(pageNo!=null){
			try {
				page = Integer.parseInt(pageNo);
			} catch (Exception e) {
				page = 1;
			}
		}
		return page;
	}
	
	/**
	 * 判断是否为数字
	 * @param str
	 * @return boolean
	 */
	public final static boolean isNumber(String str){
		try {
			Long.parseLong(str);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
	
	public final static String getUtf8Str(String str){
		String ret = "";
		if(str!=null){
			try {
				ret = new String(str.getBytes("ISO-8859-1"),"UTF-8");
				System.out.println(ret);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}
	
	/**
	 * 文件下载
	 * @param request
	 * @param response
	 * @param fileName
	 * @param in
	 * @throws IOException
	 */
	public final static void download(HttpServletRequest request , 
			HttpServletResponse response ,String fileName,InputStream in) throws IOException{
		String userAgent = request.getHeader("User-Agent");
        //针对IE或者以IE为内核的浏览器：
        if (userAgent.contains("MSIE")||userAgent.contains("Trident")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
        //非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        }
        //3.设置content-disposition响应头控制浏览器以下载的方式打开文件
        response.setHeader("content-disposition","attachment;filename="+fileName);
        int len = 0;
        //5.创建书缓冲区
        byte[] buffer = new byte[1024];
        //6.通过response对象获取OutputStream输出流对象
        OutputStream os = response.getOutputStream();
        while((len=in.read(buffer))>0){
            os.write(buffer,0,len);
        }
        in.close();
        os.close();
		
	}
}
